package git.soulbgm.common.base;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import git.soulbgm.common.pojo.*;
import git.soulbgm.utils.ServletUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author SoulBGM
 * @date 2022/03/11 13:38
 */
public class BaseController {

    private final static String[] PARSE_PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 仅支持字母、数字、下划线、空格、逗号、小数点（支持多个字段排序）
     */
    public static String SQL_PATTERN = "[a-zA-Z0-9_ ,.]+";

    /**
     * 检查字符，防止注入绕过
     */
    public static String escapeOrderBySql(String value) {
        if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
            throw new RuntimeException("参数不符合规范，不能进行查询");
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value) {
        return value.matches(SQL_PATTERN);
    }

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(parseDate(text));
            }
        });
    }

    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat();

    /**
     * 日期型字符串转化为日期 格式
     *
     * @param str str
     * @return {@link Date}
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        for (String pattern : PARSE_PATTERNS) {
            DATE_FORMAT.applyPattern(pattern);
            try {
                return DATE_FORMAT.parse(str.toString());
            } catch (ParseException ignored) {
            }
        }
        return null;
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (pageNum != null && pageSize != null) {
            String orderBy = escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtil.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest() {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse() {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(ReturnCode.SUCCESS.code);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return "redirect:" + url;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected ResultData toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected ResultData toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 返回成功
     */
    public ResultData success() {
        return ResultData.getResultData(ReturnCode.SUCCESS);
    }

    /**
     * 返回成功
     *
     * @param code 代码
     * @return {@link ResultData}
     */
    public ResultData success(ReturnCode code) {
        return ResultData.getResultData(code);
    }

    /**
     * 返回失败消息
     */
    public ResultData error() {
        return ResultData.getResultData(ReturnCode.ERROR);
    }

    /**
     * 返回成功消息
     */
    public ResultData success(String message) {
        return ResultData.getResultData(ReturnCode.SUCCESS.code, message);
    }

    /**
     * 返回成功数据
     */
    public static ResultData success(Object data) {
        return ResultData.getResultData(ReturnCode.SUCCESS, data);
    }

    /**
     * 返回失败消息
     */
    public ResultData error(String message) {
        return ResultData.getResultData(ReturnCode.ERROR.code, message);
    }

    /**
     * 返回失败消息和code
     *
     * @param code 代码
     * @return {@link ResultData}
     */
    public ResultData error(ReturnCode code) {
        return ResultData.getResultData(code);
    }

}
